import {messages} from "share/common";
import React from 'react'
import { connect } from 'react-redux'
import ResizeTable from 'components/resize-table'
import { Form, Badge, Row, Col, message, Pagination, Popover, Button, Input, Select } from 'antd'
import moment from 'moment'
import SlideFrame from  'components/slide-frame'
import auditOpinion from 'containers/finance-setting/audit-opinion/audit-opinion.service'
import NewOpinion from 'containers/finance-setting/audit-opinion/new-opinion'
import EditOpinion from 'containers/finance-setting/audit-opinion/edit-opinion'
const Search = Input.Search;
const Option = Select.Option;
class AuditOpinionDetail extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loadingClose: false,
      size: 10,
      page: 0,
      editSlideShow: false,
      slideShow: false,
      ruleInfo: {},
      dataClose: [],
      columns: [
        {title: messages('common.sequence')/*序号*/, dataIndex: 'index', render: (value, record, index) => this.state.size * this.state.page + index + 1},
        {title: messages('finance-setting.key64'/*审核意见*/), dataIndex: 'reply', width:'40%', render: value => <Popover content={value} placement='topLeft'>{value}</Popover>},
        {title: messages('finance-setting.key499'/*审核意见编码*/), dataIndex: 'code', width:'30%' },
        {title: messages('common.column.status')/*状态*/, dataIndex: 'status', render: value => { return value === 1000 ? <Badge text={messages('common.status.enable')/*启用*/} status={'success'}/> : <Badge text={messages('common.status.disable')/*禁用*/} status={'error'}/>}},
        {title: messages('common.operation')/*操作*/, width: 100, dataIndex: 'operation', render: (value, record) => <div>
          <a onClick={() => this.showEdit(record)}>{messages('common.edit')/*编辑*/}</a>
        </div>}
      ],
      rowSelection: {
        selectedRowKeys: [],
        onChange: this.onSelectChange,
        onSelect: this.onSelectItem,
        onSelectAll: this.onSelectAll
      },
      selectedDataIds: [],
      tableLoading: false,
      pagination: {
        total: 0,
      },
      page: 0,
      size: 10,
      searchValue: ''
      // onSetOfBooksId: this.props.company.setOfBooksId
    };
  };

  componentWillMount() {
    const { ruleInfo } = this.props.location.state;
    // console.log(ruleInfo)
    this.setState({
      ruleInfo: ruleInfo
    }, () => {
      this.handleChangeKey();
    })
  };

  getList = () => {
    let params = {};
    params.replyId = Number(this.state.ruleInfo.id);
    auditOpinion.getReplyChildList(params).then(res => {
      console.log(res)
      if (res.status === 200) {
        this.setState({
          dataClose: res.data.rows
        });
      }
    }).catch(err => {
      message.error(err)
    })
  }

  showEdit = (record) => {
    this.setState({
      editSlideShow: true,
      content: record
    });
  };

  //新建审核意见
  newOpinion = () => {
    this.setState({slideShow: true});
  };

  //选择项改变触发事件
  onSelectChange = (selectedRowKeys) => {
    const { rowSelection } = this.state;
    rowSelection.selectedRowKeys = selectedRowKeys;
    this.setState({ rowSelection });
  };

  //点击选择
  onSelectItem = (record, selected) => {
    let {selectedDataIds, rowSelection} = this.state;
    if(!selected){
      selectedDataIds.map((select, index) => {
        if( select.id === record.id ){
          selectedDataIds.splice(index, 1);
        }
      })
    } else {
      selectedDataIds.push(record);
    }
    this.setState({ selectedDataIds ,rowSelection:rowSelection});
  };

  //全选
  onSelectAll = (selected, selectedRows, changeRows) => {
    let {selectedDataIds} = this.state;
    if(!selected){
      changeRows.map(record => {
        selectedDataIds.map((select, index) => {
          if( select.id === record.id ){
            selectedDataIds.splice(index, 1);
          }
        })
      });
    } else {
      selectedRows.map(item => {
        let isContainer = false;
        selectedDataIds.map(select => {
          if( select.id === item.id ){
            isContainer = true;
          }
        });
        !isContainer && (selectedDataIds.push(item));
      });
    }
    this.setState({selectedDataIds});
  };

  enableOrDisabled = (statusEnum) => {
    const { selectedDataIds } = this.state;
    let ids = [];
    selectedDataIds.map((e) => {
      ids.push(e.id)
    });
    this.setState({ loadingClose: true })
    if (ids) {
      let params = {
        ids,
        statusEnum
      }
      auditOpinion.handleEnabledOrDisabled(params).then(res => {
        // console.log(res)
        if (res.data) {
          this.getList();
          this.setState({ loadingClose: false })
        }
      }).catch(err => {
        message.error(err)
        this.setState({ loadingClose: false })
      })
    }
  }

  //搜索
  handleChangeKey = (e) => {
    let value = e ? e.target.value : this.state.searchValue;
    const {page, size} = this.state;
    if (value.length > 100) {
      message.error(messages('finance-setting.key145')/*最多输入100个字符*/);
      value = value.substr(0,100);
    }
    this.setState({tableLoading: true, searchValue: value}, () => {
      this.refs.searchInput.focus();
    });
    let params = {
      page,
      size,
      searchParam: value
    };
    params.replyId = Number(this.state.ruleInfo.id);
    this.handleSearch(params);
  };

  handleSearch = (params) => {
    const { page } = this.state;
    console.log('params', params)
    auditOpinion.getReplyChildList(params).then(res => {
      this.setState({
        dataClose: res.data.rows,
        loadingClose: false,
        pagination: {
          total: res.data.total,
          onChange: this.onChangePager,
          current: page + 1
        }
      })
    }).catch(() => {
      message.error(messages('finance-setting.key65'/*出错了*/))
    });
  };

  //分页
  onChangePager = (page) => {
    if (page - 1 !== this.state.page)
      this.setState({
        page: page - 1
      }, () => {
        this.handleChangeKey();
      })
  };

  render() {
    const { columns, loadingClose, dataClose, ruleInfo, slideShow, editSlideShow, content, rowSelection, pagination, searchValue } = this.state;
    return (
      <div className="audit-opinion-detail">
        <h3 className="header-title">{messages('finance-setting.key498'/*财务审核信息*/)}</h3>
        <div style={{ marginBottom: 10 }}>审核意见详情: {ruleInfo.reply}</div>
        <div className="audit-opinion-operate">
          <Button type='primary' size='large' onClick={this.newOpinion}>{messages('finance-setting.key67'/*新建审核意见*/)}</Button>
          <Button type='primary' size='large' onClick={() => this.enableOrDisabled('USING')} style={{ margin: '0 10px' }}>{messages('common.enabled'/*启用*/)}</Button>
          <Button type='primary' size='large' onClick={() => this.enableOrDisabled('DELETED')}>{messages('common.disabled'/*禁用*/)}</Button>
          <Search
            onChange={this.handleChangeKey}
            ref={'searchInput'}
            value={searchValue}
            style={{ display: 'block', float: 'right', width: '400px', top: '50%' }}
            placeholder={messages('finance-setting.key500'/*请输入审核意见项或审核意见编码*/)}
          />
        </div>
        <ResizeTable
          rowKey={record => record.id}
          columns={columns}
          dataSource={dataClose}
          loading={loadingClose}
          bordered
          size="middle"
          style={{
            marginTop: 20
          }}
          rowSelection={rowSelection}
          pagination={pagination}
        />
        <SlideFrame show={slideShow}
                    title={messages('finance-setting.key67'/*新建审核意见*/)}
                    hasFooter={true}
                    hasMask={true}
                    params={{
                      slideShow,
                      setOfBooksId: ruleInfo.setOfBooksId,
                      mode: 'child',
                      content: ruleInfo
                    }}
                    content={NewOpinion}
                    onClose={(isRefresh) => {
                      this.setState({slideShow: false});
                      isRefresh === true && this.handleChangeKey();
                    }}
                    afterClose={(isRefresh) => {
                      this.setState({slideShow: false});
                      isRefresh === true && this.handleChangeKey();
                    }}/>
        <SlideFrame show={editSlideShow}
                    title={messages('finance-setting.key497'/*编辑审核意见*/)}
                    hasFooter={true}
                    hasMask={true}
                    params={{
                      editSlideShow,
                      content: content,
                      mode: 'child'
                    }}
                    content={EditOpinion}
                    onClose={(isRefresh) => {
                      this.setState({editSlideShow: false});
                      isRefresh === true && this.handleChangeKey();
                    }}
                    afterClose={(isRefresh) => {
                      this.setState({editSlideShow: false});
                      isRefresh === true && this.handleChangeKey();
                    }}/>
      </div>
    )
  }
}

function mapStateToProps(state) {
  return {}
}

const WrappedAuditOpinionDetail = AuditOpinionDetail;

export default connect(mapStateToProps)(WrappedAuditOpinionDetail);
